package com.zzjx.common.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zzjx.common.base.entity.IUser;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * @Author: zzjx
 * @Date: 2019/12/18 11:40
 */

@Setter
@Getter
public class JPaasUser implements SocialUserDetails, IUser {

    private static final long serialVersionUID = 1L;

    public JPaasUser() {

    }

    /**
     * 用户id
     */
    private String userId;
    /**
     * 账号
     */
    private String account;

    private String fullName;

    /**
     * 租户ID
     */
    private String tenantId;
    /**
     * 组织部门id
     */
    private String deptId;
    /**
     * 组织部门name
     */
    private String deptName;

    private String password;

    private String email;

    private String mobile;

    private List<String> roles;

    private String rootPath;

    private String status;

    private String photo;

    private String wxOpenId;

    private String ddId;

    /**
     * 是否超管。
     */
    private boolean admin = false;

    private String userType = "";

    /***
     * 权限重写
     */
    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> collection = new HashSet<>();
        if (!CollectionUtils.isEmpty(roles)) {
            roles.parallelStream().forEach(role -> collection.add(new SimpleGrantedAuthority(role)));
        }
        return collection;
    }

    @Override
    public String getUsername() {
        return this.account;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        if (IUser.STATUS_ENABLED.equals(getStatus())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String getStatus() {
        return this.status;
    }

    @Override
    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * 是否根租户管理员
     *
     * @return
     */
    public boolean isRootAdmin() {
        if (IUser.ROOT_TENANT_ID.equals(this.tenantId) && this.admin) {
            return true;
        }
        return false;
    }

    /**
     * 是否根租户管理员
     *
     * @return
     */
    public boolean isTenantAdmin() {
        if (!IUser.ROOT_TENANT_ID.equals(this.tenantId) && this.admin) {
            return true;
        }
        return false;
    }


}
